package com.gokzzz.killdemo.service.impl;

import com.gokzzz.killdemo.service.KillService;
import com.gokzzz.killdemo.service.SkuService;
import com.gokzzz.killdemo.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author gokzzz
 * @date 2022-09-10 11:02
 */
@Slf4j
@Service
public class KillServiceImpl implements KillService {
    // 获取锁的超时时间 秒
    private static final int TIMEOUT = 30 * 1000;
    // 商品Key
    private static final String KEY = "gok";

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SkuService skuService;

    @Override
    public String kill(String user) {
        //用户开抢时间
        long startTime = System.currentTimeMillis();
        //未抢到的情况下，30秒内继续获取锁
        while ((startTime + TIMEOUT) >= System.currentTimeMillis()) {
            // 查库存
            Long sku = skuService.selectSku();
            //商品是否剩余
            if (sku <= 0) {
                break;
            }
            if (redisUtil.setnx(KEY, user, 30)) {
                //用户b拿到锁
                log.info("用户{}拿到锁...", user);
                try {
                    //商品是否剩余
                    if (sku <= 0) {
                        break;
                    }

                    //模拟生成订单耗时操作，方便查看：神牛-50 多次获取锁记录
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //抢购成功，商品递减，记录用户
                    sku -= 1;
                    skuService.initSku(sku);

                    //抢单成功跳出
                    log.info("用户{}抢单成功跳出...所剩库存：{}", user, skuService.selectSku());

                    return user;
                } finally {
                    log.info("用户{}释放锁...", user);
                    //释放锁
                    redisUtil.delnx(KEY, user);
                }
            } else {
//                log.info("用户{}抢单失败...", user);
            }
        }
        return "";
    }
}
